#!/bin/bash

set -e
set -o pipefail

handle_error() {
  local exit_code=$?
  echo "Error occurred in script at line: ${1} with exit code: ${exit_code}"
  exit $exit_code
}

trap 'handle_error ${LINENO}' ERR

cur_path=$(pwd)

GIT_USER=$1
GIT_TOKEN=$2
CONAN_USER=$3
CONAN_PASSWORD=$4
BOARD_NAME=$5
AK=$6
SK=$7
ENDPOINT=$8

BUCKET_NAME="openubmc-dailybuild"
ZIP_FILENAME='repositories.zip'

chmod +x scripts/common_scripts/common.sh
source scripts/common_scripts/common.sh

function prepare_python_dependency() {
  cd ${cur_path}
  pip3 install -r scripts/publish_pipeline/publish_package/requirements.txt
  cp scripts/utils/patch/client.py /usr/local/lib/python3.12/dist-packages/obs/client.py
  chmod +r /usr/local/lib/python3.12/dist-packages/obs/client.py
}

function prepare_env() {
  prepare_software
  prepare_git $GIT_USER $GIT_TOKEN
  prepare_conan2 $CONAN_USER $CONAN_PASSWORD
  prepare_python_dependency
  prepare_bingo
}

function clone_manifest() {
  cd ${cur_path}
  if [ -d "source" ]; then
    echo "source folder is existed"
  else
    echo "source folder is not existed, and create..."
    mkdir ${cur_path}/source
  fi

  cd ${cur_path}/source
  if [ -d "manifest" ]; then
    echo "manifest folder is existed, and delete..."
    rm -rf ${cur_path}/source/manifest
  else
    echo "manifest folder is not existed"
  fi

  git clone -b main https://gitcode.com/openUBMC/manifest.git

}

function download_repositories() {
  prefix_path=$1

  cd ${cur_path}
  if [ -d ${cur_path}/source ]; then
    rm -rf ${cur_path}/source
    echo "delete source dir:${cur_path}/source"
  fi

  if [ -f ${cur_path}/${ZIP_FILENAME} ]; then
    rm -rf ${cur_path}/${ZIP_FILENAME}
    echo "delete repositories.zip:${cur_path}/source"
  fi

  wget -q https://dailybuild.openubmc.cn/${prefix_path}${ZIP_FILENAME}
  unar ${ZIP_FILENAME}
}

function check_repositories_consistency() {
  cd ${cur_path}
  find "${cur_path}/source" -maxdepth 1 -mindepth 1 -type d | while read -r subdir; do
    echo "Checking: ${subdir}"
    cd ${subdir}
    git status
    content=$(git diff --name-only -- "${subdir}" | grep -v '.gitcode') || true
    if [ ${#content} -eq 0 ]; then
      echo "No changes in ${subdir}"
    else
      echo "Changes found in ${subdir}"
      exit -1
    fi
  done
}

function build() {
  echo "===start to publish Hpm Package==="
  # upload repositories.zip
  echo "start to upload repositories.zip"
  clone_manifest
  big_version=$(jq -r '.openUBMCVersion' ${cur_path}/source/manifest/build/rootfs/etc/version.json)
  prefix_path="pre_release/${big_version}/sourcecode/"
  publish_package_script="scripts/publish_pipeline/publish_package/publish_package_prepare_source.py"
  cd ${cur_path}
  python3 ${publish_package_script} --ak=${AK} --sk=${SK} --obs_endpoint=${ENDPOINT} --bucket_name=${BUCKET_NAME} --prefix_path=${prefix_path} --zip_file_name=${ZIP_FILENAME}

  # download and unzip manifest
  echo "start to download and unzip manifest"
  download_repositories ${prefix_path}

  # check the change of repositories.zip
  echo "start to check the change of repositories.zip"
  check_repositories_consistency

  # use the manifest of repositories.zip to build
  echo "===start to use the manifest of repositories.zip to build==="
  echo "====start to publish hpm package==="
  # build and upload hpm
  cd ${cur_path}/source/manifest/
  bingo build -t publish -b "$BOARD_NAME" -bt release --stage stable
  releaseDir=$(find ${cur_path}/source/manifest/output/packet -type d -name "*$BOARD_NAME*" -print -quit)
  full_version=$(jq -r '.Version' ${cur_path}/source/manifest/temp/build_openUBMC_release_stable/tmp_root/etc/version.json)

  cd ${cur_path}
  upload_hpm_script="scripts/publish_pipeline/publish_package/publish_package_upload_file.py"
  new_prefix_path="pre_release/${big_version}/firmware/"
  python3 ${upload_hpm_script} --ak=${AK} --sk=${SK} --obs_endpoint=${ENDPOINT} --bucket_name=${BUCKET_NAME} --prefix_path=${new_prefix_path} --release=${releaseDir}

  # build and upload the qemu cpio hpm
  echo "===start to publish Qemu Package==="
  cd ${cur_path}/source/manifest
  bingo build -sc qemu

  qemu_target_filename=$(echo $(ls -l ${cur_path}/source/manifest/output/packet/inner/ | grep qemu) | awk '{print $9}')
  qemu_target_filepath="${cur_path}/source/manifest/output/packet/inner/${qemu_target_filename}"

  qemu_datagz_filename=$(echo $(ls -l ${cur_path}/source/manifest/output/ | grep qemu) | awk '{print $9}')
  qemu_datagz_filepath="${cur_path}/source/manifest/output/${qemu_datagz_filename}"

  qemu_target_sha256_filename="${qemu_target_filename/.cpio.gz/.sha256}"
  sha256sum ${qemu_target_filepath} >${qemu_target_sha256_filename}

  qemu_target_obs_key="pre_release/${big_version}/firmware/${qemu_target_filename}"
  qemu_target_sha256_key="pre_release/${big_version}/firmware/${qemu_target_sha256_filename}"

  qemu_datagz_obs_key="pre_release/${big_version}/firmware/${qemu_datagz_filename}"

  upload_obs_script="${cur_path}/scripts/common_scripts/upload_file_to_obs.py"
  python3 ${upload_obs_script} --ak=${AK} --sk=${SK} --obs_endpoint=${ENDPOINT} --obs_bucket_name=${BUCKET_NAME} --obs_key=${qemu_target_obs_key} --filename=${qemu_target_filepath}
  python3 ${upload_obs_script} --ak=${AK} --sk=${SK} --obs_endpoint=${ENDPOINT} --obs_bucket_name=${BUCKET_NAME} --obs_key=${qemu_target_sha256_key} --filename=${qemu_target_sha256_filename}
  python3 ${upload_obs_script} --ak=${AK} --sk=${SK} --obs_endpoint=${ENDPOINT} --obs_bucket_name=${BUCKET_NAME} --obs_key=${qemu_datagz_obs_key} --filename=${qemu_datagz_filepath}

}

function main() {
  prepare_env
  build
}

echo "===start to publish Package==="
main
echo "===end to publish Package==="
exit 0
